package com.learn.security.web.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import javax.servlet.ServletException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther liuhw
 * @date 2020/3/23 14:23
 * @description:
 * @since 1.0
 **/
public class LoginExpiredSessionStrategy implements SessionInformationExpiredStrategy {
    private ObjectMapper mapper = new ObjectMapper();

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "已经有另一台机器登录, 您被迫下线。" + event.getSessionInformation().getLastRequest());
        event.getResponse().setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try {
            event.getResponse().getWriter().write(mapper.writeValueAsString(map));
        } finally {
            event.getResponse().getWriter().close();
        }

    }
}
